
#include "ResMgr.h"


ResMgr* ResMgr::inst = NULL;

ResMgr::ResMgr() { }

void ResMgr::Init(const std::string rootPath) {
	this->rootPath = rootPath;
	const size_t last_slash_idx1 = rootPath.find_last_of("\\/");

	if (std::string::npos != last_slash_idx1) {
		this->rootPath.erase(last_slash_idx1, std::string::npos);
	}
}
 
ResMgr* ResMgr::GetInst() {
	if (inst == NULL)
		inst = new ResMgr();
	return inst;
}

bool ResMgr::LoadFont(const std::string fileName) {

	return true;
}

bool ResMgr::LoadModel(const std::string fileName) {

	return true;
}

bool ResMgr::LoadShader(const std::string vfileName, const std::string ffileName, Shader &shader) {
	shader = Shader((rootPath + vfileName).c_str(), (rootPath + ffileName).c_str());
	return true;
}

GLuint ResMgr::LoadTexture(const std::string fileName) {
	GLuint textureID;
	glGenTextures(1, &textureID);

	int width, height, nrComponents;
	unsigned char *data = stbi_load((rootPath + fileName).c_str(), &width, &height, &nrComponents, 0);
	if (data) {
		GLenum format;
		if (nrComponents == 1)
			format = GL_RED;
		else if (nrComponents == 3)
			format = GL_RGB;
		else if (nrComponents == 4)
			format = GL_RGBA;

		glBindTexture(GL_TEXTURE_2D, textureID);
		glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
		glGenerateMipmap(GL_TEXTURE_2D);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

		stbi_image_free(data);
	}
	else {
		Util::err("Texture failed to load at path: %s", fileName);
		stbi_image_free(data);
	}

	return textureID;
}

ResMgr::~ResMgr() { }